package com.zjitc.controller;

import com.github.pagehelper.PageInfo;
import com.zjitc.model.Product;
import com.zjitc.model.User;
import com.zjitc.service.CollectionService;
import com.zjitc.service.ProductService;
import com.zjitc.utils.UUIDUtils;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * Created by LWW on 2018/6/5.
 */
@Controller
public class CollectionController {
    @Autowired
    public CollectionService collectionService;

    @RequestMapping("/collection")
    public String collection(@RequestParam(name = "pid")String pid,
                             HttpSession session,
                             Model model) {
      User user = (User) session.getAttribute("users");
      String uid = user.getUid();
      String collectionId = UUIDUtils.getId();
      if (user == null) {
        String msg = "请先登录";
        session.setAttribute("msg", msg);
        return "/jsp/login.jsp";
      } else {
        Product products=collectionService.findByPid(pid);
        if(products==null) {
          collectionService.collection(pid, uid, collectionId);
          List<Product> collections = collectionService.findAllCollection(uid);
          model.addAttribute("collection", collections);
          return "/jsp/collection.jsp";
        }else{
          return "forward:/myCollection.do?uid="+uid;
        }
      }
    }

    @RequestMapping("/deleteCollection")
    public String dCollection(@RequestParam(name = "pid")String pid,
                             HttpSession session,
        Model model){
      User user = (User) session.getAttribute("users");
      String uid=user.getUid();
      collectionService.deleteCollection(pid,uid);
      List<Product> collections=collectionService.findAllCollection(uid);
      model.addAttribute("collection",collections);
      return "forward:/myCollection.do?uid="+uid;
    }

    @RequestMapping("/myCollection")
    public String findAllCollection(@RequestParam(name = "uid")String uid,
        Model model){
      List<Product> collections=collectionService.findAllCollection(uid);
      model.addAttribute("collection",collections);
      return  "/jsp/collection.jsp";
    }
}
